{
 "cells": [
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Visualize data fro mongodb on quick-chart \n",
    "This notebook pulls data set from [MongoDB Atlas -- The Cloud-Native Database](https://www.mongodb.com/cloud/atlas/lp/try4?utm_source=google&utm_campaign=search_gs_pl_evergreen_atlas_core-high-int_prosp-brand_gic-null_emea-ie_ps-all_desktop_eng_lead&utm_term=mongodb%20atlas&utm_medium=cpc_paid_search&utm_ad=e&utm_ad_campaign_id=19630910055&adgroup=145923638859&cq_cmp=19630910055&gad=1&gclid=Cj0KCQjwsIejBhDOARIsANYqkD2ewYCphoJvBv_op03rwncSNye4Mq_RihH9EaZKsnFK4BV-roOCOrYaAuSREALw_wcB) database and then uses [QuickChart](https://quickchart.io/) library to visualize data\n",
    "- create connection with Mongodb Atlas\n",
    "- visualize data from mongodb using QuickChart "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!pip install quickchart.io"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from quickchart import QuickChart\n",
    "from PIL import Image\n",
    "import requests\n",
    "from io import BytesIO\n",
    "import matplotlib.pyplot as plt\n",
    "from pymongo import MongoClient\n",
    "import os\n",
    "import logging\n",
    "import sys\n",
    "import re"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# database username\n",
    "database_username = os.environ.get('database_username')\n",
    "\n",
    "# database password\n",
    "password =  os.environ.get('password')\n",
    "\n",
    "# cluster url\n",
    "cluster_url = os.environ.get('cluster_url')\n",
    "\n",
    "# database name\n",
    "database = os.environ.get('database')\n",
    "\n",
    "# database collection\n",
    "collection = os.environ.get('collection')\n",
    "\n",
    "# Input parameters for chart, chart type\n",
    "chart_type = os.environ.get('chart_type')\n",
    "\n",
    "# chart data    \n",
    "chart_data = os.environ.get('chart_data')\n",
    "\n",
    "# chart labels\n",
    "chart_labels = os.environ.get('chart_labels')\n",
    "\n",
    "# chart title\n",
    "chart_title = os.environ.get('chart_title')\n",
    "\n",
    "#chart height\n",
    "chart_height = os.environ.get('chart_height')\n",
    "\n",
    "#chart width\n",
    "chart_width = os.environ.get('chart_width')\n",
    "\n",
    "# chart data\n",
    "chart_datasets = os.environ.get('chart_datasets')\n",
    "\n",
    "# path and file name for output\n",
    "output_data_image = os.environ.get('output_data_image')\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "parameters = list(\n",
    "    map(lambda s: re.sub('$', '\"', s),\n",
    "        map(\n",
    "            lambda s: s.replace('=', '=\"'),\n",
    "            filter(\n",
    "                lambda s: s.find('=') > -1 and bool(re.match(r'[A-Za-z0-9_]*=[.\\/A-Za-z0-9]*', s)),\n",
    "                sys.argv\n",
    "            )\n",
    "    )))\n",
    "\n",
    "for parameter in parameters:\n",
    "    logging.warning('Parameter: ' + parameter)\n",
    "    exec(parameter)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# MongoDB connection settings, Connection URL, Where your mongodb server is running.\n",
    "url = f\"mongodb+srv://{database_username}:{password}@{cluster_url}/test?retryWrites=true&w=majority\"\n",
    "\n",
    "# Connect to MongoDB\n",
    "client = MongoClient(url)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# MongoDB connection testing, Access specific database\n",
    "db = client[database]\n",
    "\n",
    "# Access specific collection\n",
    "collection = db[collection]\n",
    "\n",
    "# Or retrieve 100 documents\n",
    "documents = collection.find().limit(100)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Initialize empty lists for data extraction\n",
    "temperatures = []\n",
    "pressures = []\n",
    "wind_speeds = []"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Extract relevant weather data fields\n",
    "for document in documents:\n",
    "    temperatures.append(document['airTemperature']['value'])\n",
    "    pressures.append(document['pressure']['value'])\n",
    "    wind_speeds.append(document['wind']['speed']['rate'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Display extracted data\n",
    "print(\"Temperatures: \", temperatures)\n",
    "print(\"Pressures: \", pressures)\n",
    "print(\"Wind speeds: \", wind_speeds)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Define your chart data configuration\n",
    "qc = QuickChart()\n",
    "qc.height = chart_height\n",
    "qc.width = chart_width\n",
    "qc.config = {\n",
    "    'type': 'line',\n",
    "    'data': {\n",
    "        'labels': chart_labels,\n",
    "        'datasets': chart_datasets\n",
    "    },\n",
    "    'options': {\n",
    "        'scales': {\n",
    "            'y': {\n",
    "                'beginAtZero': True\n",
    "            },\n",
    "            'x': {\n",
    "                'beginAtZero': True\n",
    "            }\n",
    "        }\n",
    "    }\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# print the chart url\n",
    "print(qc.get_short_url())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Send a GET request to the image URL and retrieve the image, then display it\n",
    "response = requests.get(qc.get_short_url())\n",
    "image = Image.open(BytesIO(response.content))\n",
    "\n",
    "# Display the image\n",
    "plt.imshow(image)\n",
    "plt.axis('off')\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Convert the image to the 'RGB' mode if necessary, then save it to the specified file\n",
    "if image.mode != 'RGB':\n",
    "    image = image.convert('RGB')\n",
    "    \n",
    "# Save the image to the specified file\n",
    "image.save(output_data_image)\n",
    "\n",
    "print(\"Image saved successfully!\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "base",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.9"
  },
  "orig_nbformat": 4
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
